package com.cjp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.cjp.pojo.Category;
import com.cjp.pojo.Result;
import com.cjp.pojo.dto.CategoryAddDTO;
import com.cjp.pojo.dto.CategoryUpdateDTO;
import com.cjp.pojo.vo.CategoryVO;
import com.cjp.service.ICategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/category")
@RequiredArgsConstructor
public class CategoryController {

    private final ICategoryService categoryService;

    @GetMapping
    public Result<List<CategoryVO>> list() {
        List<CategoryVO> categoryVOList = categoryService.listCategory();
        return Result.success(categoryVOList);
    }

    @PostMapping
    public Result addCategory(@RequestBody @Validated CategoryAddDTO categoryAddDTO) {
        Category category = BeanUtil.copyProperties(categoryAddDTO, Category.class);
        categoryService.addCategory(category);
        return Result.success();
    }

    @PutMapping
    public Result updateCategory(@RequestBody @Validated CategoryUpdateDTO categoryUpdateDTO) {
        Category category = BeanUtil.copyProperties(categoryUpdateDTO, Category.class);
        categoryService.updateCategory(category);
        return Result.success();
    }

    @GetMapping("/detail")
    public Result<CategoryVO> detail(Long id) {
        Category category = categoryService.getById(id);
        CategoryVO categoryVO = BeanUtil.copyProperties(category, CategoryVO.class);
        return Result.success(categoryVO);
    }

    @DeleteMapping
    public Result deleteCategory(Long id) {
        categoryService.removeById(id);
        return Result.success();
    }
}
